<!--出院登记-->
<template>
  <div>
    <el-dialog :title="title" ref="form" :model="form" :visible.sync="dialogVisible" :before-close="closeDialog"
               :close-on-click-modal="false"
               v-on:open="loadData">

      <el-row style="height: 30px">
        <el-col :span="12">
            <el-radio class="radio" v-model="registerType" :label="1">人脸识别</el-radio>
              <img v-show="matchResult" src="../../../../static/img/right.png" width="15px" height="15px"/>
        </el-col>
        <!--<el-col :span="12">-->
            <!--<el-radio class="radio" v-model="registerType" :label="2">指纹比对</el-radio>-->
              <!--<img v-show="verifyResult" src="../../../../static/img/right.png" width="50px" height="50px"/>-->
        <!--</el-col>-->
      </el-row>
      <div v-show="registerType == 1">
      <el-row>
        <el-col :span="24" class="textface">
          请拍摄受试者[&nbsp;{{form.name}}&nbsp;]（筛选号：{{form.num}}）的面部以核验身份。
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">摄像头</div>
            <div style="text-align: center;padding:2px;">
              <video id="video" width="200px" height="150px" autoplay ></video>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8" style="padding-left:5px;">
          <el-card class="box-card">
            <div slot="header" class="clearfix">照片</div>
            <div style="text-align:center;padding:2px;">
              <canvas id="canvas" v-show="photo==true" style="width:200px;height: 150px;"></canvas>
              <img src="/static/img/man.png" v-show="photo!=true" height="150px">
            </div>
          </el-card>
        </el-col>
        <el-col :span="8" style="padding-left:5px;">
          <el-card class="box-card">
            <div slot="header" class="clearfix">历史照片</div>
            <div style="text-align: center;padding:2px;min-height:150px;">
              <img id="img" :src="'data:image/jpg;base64,'" height="150px"/>
              <!--<img id="img" :src="" height="150px"/>-->
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="padding:10px;">
          <span v-show="errMsg!=''" style="color:red;float:left;">{{errMsg}}</span>
          <div v-show="matchResult" style="float:left;">
            核对成功，点击【确认】完成{{form.hospitalStatus == 1 ? '出院' : '入院'}}记录操作
          </div>
          <div class="pull-right">
            <el-button type="primary" @click.native="ChangeActive" v-show="matchResult">{{addBtnTxt}}</el-button>
            <el-button type="primary" @click="matchSubjectFace" :disabled="matchFaceClick">拍照比对</el-button>
            <el-button @click.native="closeDialog">关闭</el-button>
          </div>
        </el-col>
      </el-row>
      </div>
      <div v-show="registerType == 2">
      <!--
          指纹认证出入院操作
      -->
      <el-row>
        <el-col :span="24">
          请采集受试者[&nbsp;{{form.name}}&nbsp;]（筛选号：{{form.num}}）的{{form.finger}}指纹以核验身份。
        </el-col>
      </el-row>
      <el-row style="margin-left: 80px">
        <el-col :span="10">
          <el-card class="box-card">
            <div slot="header" class="clearfix">已留存指纹</div>
            <div style="text-align: center;padding:2px;height: 150px;width: 200px">
              <img src="/static/img/finger.png" v-show="form.fingerImg == ''||form.fingerImg == undefined"/>
              <img :src="form.fingerImg" style="height: 150px;width:150px;" v-show="!(form.fingerImg == ''||form.fingerImg == undefined)"/>
            </div>
          </el-card>
        </el-col>
        <el-col :span="10" style="padding-left:20px;">
          <el-card class="box-card">
            <div slot="header" class="clearfix">当前采集指纹</div>
            <div style="text-align:center;padding:2px;height: 150px;width: 200px">
              <img src="/static/img/finger.png" v-show="fingerPhoto == false"/>
              <img :src="fingerImg2" v-show="fingerPhoto != false" style="height: 150px;width:150px;"/>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div style="height: 15px">
        <el-row style="margin-left: 150px">
          <el-col :span="24">
             <span style="font-weight: bolder" v-show="errMsgFinger!=''">
                 {{errMsgFinger}}
             </span>
            <span v-show="verifyResult">
                 核对成功，点击【确认】完成{{form.hospitalStatus == 1 ? '出院' : '入院'}}记录操作
             </span>
          </el-col>
        </el-row>
      </div>
      <el-row>
        <el-col :span="24" style="padding:10px;">
          <div class="pull-right">
            <el-button type="primary" @click="ChangeActive" v-show="verifyResult">确认{{form.hospitalStatus == 1 ? '出院' : '入院'}}</el-button>
            <el-button type="primary" @click="changeFingerTemplete" :disabled="matchFingerClick">指纹比对</el-button>
            <el-button @click.native="closeDialog">关闭</el-button>
          </div>
        </el-col>
      </el-row>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import http from '../../../api/http'
  export default {
    data() {
      return {
        registerType:1,
        matchResult: false,//人脸匹配结果
        verifyResult: false,//指纹匹配结果
        fingerImg2: '',    //匹配图片
        template: '',
        template2: '',     //匹配模版
        form: {},
        title: '',         //设置标题默认为空串
        addBtnTxt: '',
        regFeature: '',    //存储之前录入的指纹
        verFeature: '',    //存储现在录入的指纹
        featureData: {},//存储指纹数据
        context: null,
        mediaStream: null,
        video: null,//设备摄像头
        photo: false,
        matchFaceClick: false,
        errMsg: '',
        errMsgFinger:'',
        fingerPhoto: false,
        matchFingerClick: false
      }
    },
    props: {
      registerDialogVisible: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      dialogVisible: {
        get: function () {
          return this.registerDialogVisible
        },
        set: function () {
        }
      }
    },
    methods: {
      openVideo() {
        var vm = this;

        vm.video = vm.$el.querySelector("#video");

        var canvas = vm.$el.querySelector("#canvas");

        vm.context = canvas.getContext("2d");
        //获取摄像头对象
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

        navigator.getUserMedia({
          video: true,    // 控制视频设备
//          audio: true  // 控制音频设备
        }, gotStream, noStream); //打开摄像头
        //成功打开摄像头
        function gotStream(stream) {
          vm.mediaStream = stream;//获取视频输入输出流
          vm.video.src = URL.createObjectURL(stream);
          vm.video.onerror = function () {
            stream.stop();
          }
          stream.onended = noStream;
          vm.video.onloadedmetadata = function () {
//            alert("成功打开摄像头")
          };
        }

        //打开摄像头失败
        function noStream(error) {
//          vm.$message.error({message: '开启摄像头异常！'});
          vm.errMsg = "开启摄像头异常！";
        }
      },
      //人脸比对
      matchSubjectFace(oldImg, newImg) {
        this.context.drawImage(video, 0, 0, 300, 150);
        // 获取base64位格式的图片
        console.log(this.context)
        // 
        var imgstr = canvas.toDataURL();
        this.photo = true;
        var vm = this;
        vm.errMsg = "";
        vm.matchFaceClick = true;
        var avatorData = {"img": imgstr, "cardid": this.form.cardid};
        http.postData(vm, '/lib/face/verify', avatorData, function (resp) {
          var ret = resp.body;
          if (ret.code == 111) {
            vm.matchResult = true;
            vm.$message.success({message: ret.msg});
          } else {
            vm.$message.error({message: ret.msg});
          }
          vm.matchFaceClick = false;
        });
      },
      matchSubjectFeature(finger_1, finger_2){
        var vm = this;
        vm.featureData = {"reg": finger_1, "ver": finger_2};
        var jsonData = JSON.stringify(vm.featureData);
        http.postDataFullURL(vm, 'http://127.0.0.1:22001/zkbioonline/fingerprint/verify', jsonData, function (result) {
          var result = result.body
          var ret = result.ret;
          if (ret == 0) {
            var score = result.score;
            if (score >= 75) {
              //比对成功 - 显示出院按钮
              vm.verifyResult = true;
              vm.matchFingerClick = true;
            }
            else {
              vm.errMsgFinger = "对比失败,请重新采集指纹";
            }
          }
        });
      },
      changeFingerTemplete(){
        var vm = this;
        vm.template2 = '';
        vm.fingerImg2 = '';
        vm.verifyResult = false;
        vm.fingerPhoto = false;
        vm.matchFingerClick = true;
        var base64Head = 'data:image/jpg;base64,';

        http.getDataFullURL(vm, 'http://127.0.0.1:22001/zkbioonline/fingerprint/beginCapture?type=2&FakeFunOn=0', function (resp) {
          var data = resp.bodyText;
          data = JSON.parse(data);
          if (data.ret == 0) {
            vm.$message.success({title: '操作成功', message: "请按压手指"});
            //获取指纹图片
            setTimeout(function () {
              http.getDataFullURL(vm, 'http://127.0.0.1:22001/zkbioonline/fingerprint/getImage', function (resp) {
                var data = resp.bodyText;
                data = JSON.parse(data);
                if (data.ret == 0) {
                  vm.fingerImg2 = base64Head + data.data.jpg_base64;
                  vm.fingerPhoto = true;
                  //获取指纹模板
                  http.getDataFullURL(vm, 'http://127.0.0.1:22001/zkbioonline/fingerprint/getTemplate', function (resp) {
                    var data = resp.body;
                    console.log(data)
                    if (data.ret == 0) {
                      vm.template2 = data.data.template;
                      // 进行指纹比对
                      vm.matchSubjectFeature(vm.template, vm.template2);
                    }
                  })
                }
              })
            }, 3000);


          } else if (data.ret != 0) {
            vm.$message.error({title: '操作失败', message: "获取指纹信息失败，请重试!"});
          }
        }, function (err) {
          vm.$message.error({title: '操作失败', message: "获取指纹设备失败，请检查是否连接正确！"});
        });
        vm.matchFingerClick = false;
      },
      closeDialog() {
        this.context.clearRect(0, 0, 180, 158);
        this.matchResult = false;
        if (this.mediaStream)
          this.mediaStream.getVideoTracks()[0].stop();
        this.matchFaceClick = false;
        this.$emit('closeRegisterDialog');
        this.errMsg = "";
        this.template2 = '';
        this.fingerImg2 = '';
        this.matchResult = false;
        this.verifyResult = false;
        this.fingerPhoto = false;
        this.errMsgFinger = '';
      },
      loadData() {
        var vm = this;
        //  页面打开后触发调用摄像头的方法
        setTimeout(function () {
          vm.openVideo();
        }, 300);
        vm.photo = false;
        vm.matchFingerClick = false;
        http.postData(vm, "/pt/subjects/detail/" + vm.$parent.currentSubjectId, {}, function (resp) {
          var data = resp.body;
          console.log(resp)
          // console.log(resp.body.value)
          var faceImgss= document.getElementById("img");
          faceImgss.src=resp.body.msg;
          if (data.code == 111) {
            vm.form = data.value;
            vm.template = vm.form.fingerprint;
            if (vm.form.hospitalStatus === 0) {
              vm.addBtnTxt = '确认入院';
              vm.title = '入院登记';
            } else {
              vm.addBtnTxt = '确认出院';
              vm.title = "出院登记"
            }
          } else {
            vm.$notify.error({title: '操作失败'});
          }
        });
      },
      ChangeActive() {
        var vm = this;
        http.postData(vm, "/pt/subjects/active/" + vm.$parent.currentSubjectId + "-" + vm.$parent.currentHospitalStatus, {}, function (resp) {

          if (resp.body.code === '111') {
            vm.$notify.success({title: '操作成功'});
            vm.$emit('onSubmit');
            vm.closeDialog();
          } else {
            vm.$notify.error({title: '操作失败'});
          }
        });
      }
    },
  }
</script>
<style>
    #img{
      width: 200px;
      height: 150px;
    }
  .textface{
    margin-bottom: 10px;
  }
</style>
